#include "Message.h"
#include <string.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int Message_write(struct member * username_src)
{
	int Message_goal_fd;
	char input_buf[1000]={0};
	char dir[100]={0};
	char date[100]={0};
	char buf[1000]={0};
	time_t t;
	char username_goal[100]={0};
	int send_len=0;
	int recev_len=0;
	int ret=0;


	//创建一个名字为Message的目录
	strcpy(dir,"Message");
	mkdir(dir,0777);


	strcpy(input_buf,"请输入您要留言的用户名：\n");
	send_len=strlen(input_buf)+1;	
	ret=write(username_src->fd,&send_len,4);
	ret=write(username_src->fd,input_buf,send_len);
	//ret=read(username_src->fd,&recev_len,4);
	//ret=read(username_src->fd,username_goal,recev_len);
	if(recv_from_client(username_src->fd, username_goal))
				return;


	strcpy(input_buf,"请输入您的留言内容：\n");
	send_len=strlen(input_buf)+1;	
	ret=write(username_src->fd,&send_len,4);
	ret=write(username_src->fd,input_buf,send_len);
	//ret=read(username_src->fd,&recev_len,4);
	//ret=read(username_src->fd,buf,recev_len);
	if(recv_from_client(username_src->fd, buf))
				return;


	//dir赋值为写目标msg文件的路径，并打开文件
	sprintf(dir,"%s%s%s%s",dir,"/",username_goal,".msg");
	Message_goal_fd=open(dir,O_WRONLY|O_APPEND|O_CREAT,0777);
	//获取当地时间
	time(&t);
	strcpy(date,ctime(&t));
	sprintf(input_buf,"%s%s%c%s%s%c%s%s","留言者：",username_src->name,'\n',"留言内容：",buf,'\n',"留言时间：",date);
	printf("%s\n",input_buf);
	write(Message_goal_fd,input_buf,strlen(input_buf));
	close(Message_goal_fd);

	strcpy(input_buf,"留言成功，请按任意键继续！\n");
	send_len=strlen(input_buf)+1;	
	ret=write(username_src->fd,&send_len,4);
	ret=write(username_src->fd,input_buf,send_len);
	//ret=read(username_src->fd,&recev_len,4);
	//ret=read(username_src->fd,buf,recev_len);
	if(recv_from_client(username_src->fd, buf))
				return;

}

int Message_read(struct member * username_src)
{
	

	//int client_read_fd=0;
	//int username_src->fd=0;
	int ret=0;
	char buf[100]={0};
	int send_len=0;
	int recev_len=0;
	char file_content[10200]={0};
	int Message_goal_fd;
	char input_buf[10000]={0};
	char dir[100]={0};
	time_t t;
	//client_read_fd=open("client_fifo_read",O_RDWR);
	//username_src->fd=open("client_fifo_write",O_RDWR);
	
	
	
	strcpy(dir,"Message");
	mkdir(dir,0777);
	sprintf(dir,"%s%s%s%s",dir,"/",username_src->name,".msg");
	Message_goal_fd=open(dir,O_RDONLY|O_APPEND|O_CREAT,0777);
	ret=read(Message_goal_fd,input_buf,10000);
	if(ret>0){
	strcpy(file_content,input_buf);
	sprintf(file_content,"%s%s",file_content,"\n请输入任意字符发送并继续操作！\n");
	send_len=strlen(file_content)+1;
	ret=write(username_src->fd,&send_len,4);
	ret=write(username_src->fd,file_content,send_len);
	//ret=read(username_src->fd,&recev_len,4);
	//ret=read(username_src->fd,buf,recev_len);
	if(recv_from_client(username_src->fd, buf))
					return;
	close(Message_goal_fd);
	}else
	{
	
	}
	remove(dir);
	return 0;
}
